package com.polaris.live.ui.message.fragment

import android.os.Bundle
import androidx.core.os.bundleOf
import androidx.lifecycle.viewModelScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.StringUtils
import com.polaris.live.R
import com.polaris.live.adapter.message.SessionAdapter
import com.polaris.live.adapter.message.SessionViewHolder
import com.polaris.live.common.cacha.CacheUtil
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.constant.CommonConst
import com.polaris.live.common.manager.CoroutineScopeManager
import com.polaris.live.common.mvvm.base2.BaseVbFragment
import com.polaris.live.common.network.parseState
import com.polaris.live.common.network.state.ResultState
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.constant.LiveConst
import com.polaris.live.constant.UserConst
import com.polaris.live.databinding.FragmentMessageSessionBinding
import com.polaris.live.im.db.database.AppDatabase
import com.polaris.live.im.db.entity.SessionEntity
import com.polaris.live.im.manager.ImMessageManager
import com.polaris.live.im.manager.ImSessionManager
import com.polaris.live.im.sfs.COMMAND_SINGLE_MESSAGE
import com.polaris.live.im.sfs.COMMAND_STRANGER_MESSAGE
import com.polaris.live.im.sfs.COMMAND_SYSTEM_MESSAGE
import com.polaris.live.im.sfs.SYSTEM_USER_ID
import com.polaris.live.im.sfs.bean.chat.ReceiveSingleMessage
import com.polaris.live.im.utils.toEmptySession
import com.polaris.live.im.utils.toNewSession
import com.polaris.live.im.utils.toSessionEntity
import com.polaris.live.im.utils.toStrangerSession
import com.polaris.live.manager.LiveStateManager
import com.polaris.live.manager.UserStateManager
import com.polaris.live.resp.event.UserUpdateEvent
import com.polaris.live.translation.R.string
import com.polaris.live.ui.message.fragment.dialog.MessageSingleDialogFragment
import com.polaris.live.ui.message.fragment.dialog.MessageStrangerDialogFragment
import com.polaris.live.ui.party.PartyUserStateUtil
import com.polaris.live.utils.CommonUtils.toBoolean
import com.polaris.live.utils.fragment.showNewDialogFragment
import com.polaris.live.utils.image.ImageUtils
import com.polaris.live.utils.interfaces.OnAutoRefreshListener
import com.polaris.live.utils.route.RoutePath
import com.polaris.live.utils.route.Router
import com.polaris.live.utils.route.RouterUtils
import com.polaris.live.utils.state.copyState
import com.polaris.live.utils.state.getDisplayIndices
import com.polaris.live.utils.state.getDisplayPosition
import com.polaris.live.viewmodel.message.MessageSessionViewModel
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.concurrent.TimeUnit

/**
 * MessageSessionFragment
 *
 * @author Created by lucas on 2023/10/27 15:06
 */
class MessageSessionFragment :
    BaseVbFragment<MessageSessionViewModel, FragmentMessageSessionBinding>(),
    OnAutoRefreshListener {

    private val mAdapter by lazy { SessionAdapter() }

    private lateinit var mSessionCommand: String
    private var mNestedPage: Boolean = false
    private var mNeedClickAvatar: Boolean = true

    //如果这个主播id不为空就代表是直播间打开的半弹窗  那么就要把这个主播的session放到第一位
    private val mAnchorId by lazy { arguments?.getLong("anchorId", -1L) ?: -1L }

    //第一次加载时是否为空，存在一种情况，因为点击消息模块过快，未加载数据之前已经试图刷新用户状态，这时候无法获取状态
    private var firstLoadSessionEmpty: Boolean = true

    //客服消息，如果获取系统消息比客服块，那这个就是空，如果慢就有值
    private var mCustomerSessionEntity: SessionEntity? = null

    override fun initView(savedInstanceState: Bundle?) {
        EventBus.getDefault().register(this)
        mSessionCommand = arguments?.getString("sessionCommand")
            ?: throw IllegalArgumentException("sessionCommand is null")
        mNestedPage = arguments?.getBoolean("nestedPage") ?: false
        mNeedClickAvatar = arguments?.getBoolean(LiveConst.Params.NEED_CLICK_AVATAR, true) ?: true

        mViewModel.sessionCommand = mSessionCommand
        initView()
        initObserver()
        initListener()

        getSessionData()
        if (mSessionCommand == COMMAND_SYSTEM_MESSAGE) mViewModel.getCustomerService()
    }

    /**
     * 用户数据更新
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun eventBusUserUpdate(event: UserUpdateEvent) {
        mViewModel.viewModelScope.launch {
            AppDatabase.instance.sessionListDao().getSession(UserManager.getUserId(), event.userId)
                ?.let {
                    withContext(CoroutineScopeManager.mainDispatcher) {
                        val currentPosition = findSession(it)
                        if (currentPosition != -1) {
                            mAdapter.setData(currentPosition, it)
                        }
                    }
                }
        }
    }

    private fun initView() {
        mAdapter.setSessionCommand(mSessionCommand)

        mBinding.refreshView.setEnableRefresh(false)

        mBinding.refreshView.apply {
            recycler.layoutManager = LinearLayoutManager(context)
            recycler.itemAnimator = null
            attachedAdapter(mAdapter, mViewModel).observeList(
                this@MessageSessionFragment,
                mViewModel.pageSize,
                mViewModel.sessionLiveData
            ) { state ->
                //第一次加载完成新数据需要更新用户状态
                if (firstLoadSessionEmpty && state is ResultState.Success && state.data.isNotEmpty()) {
                    updateUserStateObserve(state.data
                        .filter { it.command == COMMAND_SINGLE_MESSAGE }
                        .map { it.otherId })
                    firstLoadSessionEmpty = false
                    mCustomerSessionEntity?.let {
                        if (mAdapter.data.size >= getCustomerPosition()) {
                            mAdapter.addData(getCustomerPosition(), it)
                        }
                    }
                }
                //mAnchorId不为空和请求成功的情况
                if (mAnchorId != -1L) {
                    val indexOfFirst = mAdapter.data.indexOfFirst { it.otherId == mAnchorId }
                    //没有数据构造一条临时数据
                    if (indexOfFirst == -1) {//去请求主播的简单数据
                        mViewModel.getInfoAnchor(mAnchorId)
                    } else if (indexOfFirst != 0) {//不在第一位塞到第一位
                        val anchorItem = mAdapter.getItemOrNull(indexOfFirst) ?: return@observeList
                        mAdapter.removeAt(indexOfFirst)
                        mAdapter.addData(0, anchorItem)
                        mBinding.refreshView.recycler.scrollToPosition(0)
                    }
                }
            }
        }
    }

    private fun initObserver() {
        //接收消息的用户信息后更新会话信息
        mViewModel.receiveLiveData.observe(this) {
            invokeReceiveSingleMessage(it)
        }
        //获取最后一条陌生人的消息
        mViewModel.lastStrangerMessageLiveData.observe(this) {
            val strangerItem = mAdapter.data.getOrNull(getStrangerPosition())
            if (strangerItem?.command == COMMAND_STRANGER_MESSAGE) {
                if (it == null) {
                    mAdapter.setData(getStrangerPosition(), strangerItem.toEmptySession())
                } else {
                    val (user, message) = it
                    mAdapter.setData(
                        getStrangerPosition(),
                        strangerItem.toStrangerSession(message, user)
                    )
                }
            }
        }
        //监听消息接收
        ImMessageManager.observeReceive(this) {
            //如果是系统消息，固定找第一个
            if (it.command == COMMAND_SYSTEM_MESSAGE) {
                receiveSystemMessage(it)
            } else if (it.command == COMMAND_SINGLE_MESSAGE) {
                receiveSingleMessage(it)
            }
        }
        //监听自己的消息发送
        ImMessageManager.observeSend(this) { _, message ->
            val position = mAdapter.data.indexOfLast {
                it.command == message.command && it.otherId == message.recipient
            }

            if (isSystemMessage()) {
                //自己发送尝试清除陌生人消息
                clearCurrentStranger(message.otherId)

                if (position == -1) {
                    mViewModel.getSendInfoBasic(message)
                } else {
                    val newItem = mAdapter.data[position].toNewSession(message)
                    if (newItem.isUserEmpty()) {
                        mViewModel.getSendInfoBasic(message)
                    } else {
                        invokeUpdateSession(position, newItem)
                    }
                }
            } else {
                if (position != -1) {
                    mAdapter.removeAt(position)
                }
            }
        }
        //监听消息陌生人状态变化
        ImSessionManager.observeStranger(this, !isSystemMessage()) { session ->
            //自己发送的然后变为非陌生的下面已经处理了，这里只处理非陌生变陌生
            if (session.isStranger()) {
                if (isSystemMessage()) {
                    val currentPosition = findSession(session)
                    if (currentPosition != -1) {
                        mAdapter.removeAt(currentPosition)
                    }
                    mViewModel.getLastStrangerMessage()
                } else {
                    val index = mAdapter.data.indexOfFirst {
                        it.timestamp != null
                                && session.timestamp != null
                                && session.timestamp >= it.timestamp
                    }
                    if (index == -1) {
                        mAdapter.addData(session)
                    } else {
                        mAdapter.addData(index, session)
                    }
                }
            }
        }
        //监听消息清除
        ImSessionManager.observeDelete(this) {
            //如果是陌生人消息
            if (isSystemMessage() && it.isStranger()) {
                clearCurrentStranger(it.otherId)
            } else {
                val currentPosition = findSession(it)
                if (currentPosition != -1) {
                    mAdapter.removeAt(currentPosition)
                }
            }
        }
        //监听会话列表的未读数变化
        ImSessionManager.observeUnreadCount(this) { _, strangerUnreadCount, session, unreadCount ->
            if (isSystemMessage()) {
                val strangerItem = mAdapter.data.getOrNull(getStrangerPosition())
                if (strangerItem?.command == COMMAND_STRANGER_MESSAGE) {
                    mAdapter.setData(
                        getStrangerPosition(),
                        strangerItem.copy(unreadCount = strangerUnreadCount)
                    )
                }
            }

            if (unreadCount <= 0) {
                val currentPosition = findSession(session)
                if (currentPosition != -1) {
                    val currentItem = mAdapter.data[currentPosition]
                    val currentUnreadCount = currentItem.unreadCount ?: 0
                    val currentStrangerUnreadCount = currentItem.strangerUnreadCount ?: 0
                    if (currentUnreadCount > 0 || currentStrangerUnreadCount > 0) {
                        currentItem.unreadCount = 0
                        currentItem.strangerUnreadCount = 0
                        mAdapter.setData(
                            currentPosition,
                            currentItem
                        )
                    }
                }
            }
        }
        //监听当前列表用户状态
        UserStateManager.observe(this, {
            getDisplayUserIds()
        }, { messages ->
            if (!isCreated()) {
                return@observe
            }
            //如果没渲染出来直接获取所有的更新
            val indices = mBinding.refreshView.recycler.getDisplayIndices(mAdapter.data)

            messages.forEach { message ->
                for (i in indices) {
                    val item = mAdapter.getItem(i)
                    if (item.userBasic?.userId == message.state.userId) {
                        item.updateUserBasic(item.userBasic?.copyState(message), true)
                        mAdapter.notifyItemChanged(i)
                        break
                    }
                }
            }
        })
        //客服
        mViewModel.customerLiveData.observe(this) { resultState ->
            parseState(resultState, {
                if (it.display.toBoolean()) {
                    val seesionEntity = SessionEntity(
                        command = CommonConst.Customer.command,
                        userId = UserManager.getUserId(),
                        otherId = CommonConst.Customer.cusstomerId,
                        content = it.url
                    )
                    val size = mAdapter.data.size
                    //如果速度过快，还没有加载出陌生人消息和系统消息时，就把客服放到第一个
                    if (size >= getCustomerPosition()) {
                        mAdapter.addData(getCustomerPosition(), seesionEntity)
                    } else {
                        mCustomerSessionEntity = seesionEntity
                    }
                }
            })
        }
        //获取客服红点
        mViewModel.mCustomerReadLiveData.observe(this) { resultState ->
            parseState(resultState, {
                val showReadCount = if (it.haveUnread) 1L else 0L
                if (mCustomerSessionEntity != null) {
                    mCustomerSessionEntity?.unreadCount = showReadCount
                } else {
                    val indexOfFirst = mAdapter.data.indexOfFirst { it.command == CommonConst.Customer.command }
                    if (indexOfFirst == -1) return@parseState
                    val item = mAdapter.getItemOrNull(indexOfFirst) ?: return@parseState
                    item.unreadCount = showReadCount
                    mAdapter.notifyItemChanged(indexOfFirst)
                }
            })
        }
        //获取到了主播信息
        mViewModel.infoLiveData.observe(this) { resp ->
            mAdapter.addData(0, resp)
            mBinding.refreshView.recycler.scrollToPosition(0)
        }

    }

    private fun initListener() {
        mAdapter.setOnItemClickListener { _, _, position ->
            goMessageDetail(position)
        }

        mAdapter.setOnItemChildClickListener { _, v, position ->
            val item = mAdapter.data[position]
            if (item.command != COMMAND_SYSTEM_MESSAGE && item.command != COMMAND_STRANGER_MESSAGE) {
                when (v.id) {
                    R.id.avatar -> {
                        if (mNeedClickAvatar) {
                            if (mNestedPage) {
                                if (PartyUserStateUtil.inTheGame) {
                                    ToastGravity.showGravity(string.party_paly_game_click_avater)
                                    return@setOnItemChildClickListener
                                }
                                if (PartyUserStateUtil.inTheGameSeat) {
                                    ToastGravity.showGravity(string.party_paly_seat_click_avater)
                                    return@setOnItemChildClickListener
                                }
                            }

                            if (LiveStateManager.isLiving()) {
                                goMessageDetail(position)
                            } else {
                                if (item.command == CommonConst.Customer.command) return@setOnItemChildClickListener
                                Router.builder(RoutePath.USER_SPACE_ACTIVITY)
                                    .withInt("page", UserConst.From.SINGLE)
                                    .withLong("userId", item.otherId)
                                    .run {
                                        val userBasic = item.userBasic
                                        if (userBasic != null) {
                                            withAny("userBasic", userBasic)
                                        } else {
                                            this
                                        }
                                    }
                                    .navigation(requireActivity())
                            }
                        }
                    }
                }
            }
        }
        mAdapter.setOnItemLongClickListener { _, position ->
            val holder = mBinding.refreshView.recycler.findViewHolderForAdapterPosition(position)
            if (holder !is SessionViewHolder) {
                return@setOnItemLongClickListener
            }

            //这里发生过崩溃，所以加了一个判断
            val item = mAdapter.getItemOrNull(position)
            if (item != null) {
                if (mAnchorId != -1L && mAnchorId == item.otherId) return@setOnItemLongClickListener

                val string = if (item.command == COMMAND_SINGLE_MESSAGE) {
                    arrayOf(StringUtils.getString(string.delete_session))
                } else {
                    arrayOf(StringUtils.getString(string.clear_session))
                }

                holder.builder.asAttachList(string, null) { index, _ ->
                    when (index) {
                        0 -> {
                            mViewModel.clearSession(item)

                            if (item.command == COMMAND_SINGLE_MESSAGE) {
                                mAdapter.removeAt(position)
                            } else {
                                //todo 这里需要修改，只清除未读数
                                mAdapter.setData(position, item.toEmptySession())
                            }
                        }
                    }
                }.show()
            }
        }

        mBinding.refreshView.recycler.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    updateUserStateObserve()
                }
            }
        })
    }

    //展示最新的一条
    fun scrollToTop() {
        if (!isCreated()) {
            return
        }
        mBinding.refreshView.recycler.scrollToPosition(0)
    }

    private fun goMessageDetail(position: Int) {
        val item = mAdapter.data[position]
        if (item.command == COMMAND_SYSTEM_MESSAGE) {
            if (mNestedPage) {
                gotoSingleDialog(SYSTEM_USER_ID)
            } else {
                Router.builder(RoutePath.MESSAGE_ACTIVITY)
                    .withInt("page", UserConst.From.SINGLE)
                    .apply {
                        item.userBasic?.also {
                            withString("nickname", it.nickname)
                            withString("avatar", it.avatar)
                            it.avatarFrame?.also { af -> withString("avatarFrame", af) }
                            it.chatBubble?.also { cb -> withString("chatBubble", cb) }
                        }
                    }
                    .withLong("userId", SYSTEM_USER_ID)
                    .navigation(requireActivity())
            }
        } else if (item.command == COMMAND_STRANGER_MESSAGE) {
            if (mNestedPage) {
                gotoStrangerDialog()
            } else {
                Router.instance.setPath(RoutePath.MESSAGE_STRANGER_ACTIVITY)
                    .navigation(requireActivity())
            }
        }  else if (item.command == CommonConst.Customer.command) {
            item.content?.let { RouterUtils.routerCustomerService(ImageUtils.imgPath(it)) }
        }else {
            if (mNestedPage) {
                gotoSingleDialog(
                    item.otherId,
                    item.userBasic?.avatar,
                    item.userBasic?.avatarFrame,
                    null
                )
            } else {
                Router.builder(RoutePath.MESSAGE_ACTIVITY)
                    .withInt("page", UserConst.From.SINGLE)
                    .apply {
                        item.userBasic?.also {
                            withString("nickname", it.nickname)
                            withString("avatar", it.avatar)
                            it.avatarFrame?.also { af -> withString("avatarFrame", af) }
                            it.chatBubble?.also { cb -> withString("chatBubble", cb) }
                        }
                    }
                    .withLong("userId", item.otherId)
                    .navigation(requireActivity())
            }
        }
    }

    override fun initData() {
        //如果进入了陌生人会话，清除陌生人的所有未读数
        if (!isSystemMessage()) {
            mViewModel.clearStrangerUnreadCount()
        }
    }

    private fun updateUserStateObserve(userIds: List<Long> = getDisplayUserIds()) {
        if (firstLoadSessionEmpty && userIds.isNotEmpty()) {
            firstLoadSessionEmpty = false
        }

        UserStateManager.updateUserObserve(this, userIds)
    }

    private fun getDisplayUserIds(): List<Long> {
        val position = mBinding.refreshView.recycler.getDisplayPosition(mAdapter.data)
            ?: return emptyList()

        return mAdapter.data.subList(position.firstPosition, position.lastPosition)
            .filter { it.command == COMMAND_SINGLE_MESSAGE }
            .map { it.otherId }
    }

    private fun clearCurrentStranger(otherId: Long) {
        val strangerItem = mAdapter.data.getOrNull(getStrangerPosition())
        if (strangerItem?.command == COMMAND_STRANGER_MESSAGE && otherId == strangerItem.otherId) {
            mViewModel.getLastStrangerMessage()
        }
    }

    private fun gotoSingleDialog(
        otherId: Long,
        avatar: String? = null,
        avatarFrame: String? = null,
        mChatBubble: String? = null,
    ) {
        childFragmentManager.showNewDialogFragment(
            MessageSingleDialogFragment(
                otherId,
                avatar,
                avatarFrame,
                mChatBubble,
                mNestedPage,
                needClickAvatar = mNeedClickAvatar
            ), FRAGMENT_TAG
        )
    }

    private fun gotoStrangerDialog() {
        childFragmentManager.showNewDialogFragment(
            MessageStrangerDialogFragment().apply {
                arguments = bundleOf(LiveConst.Params.NEED_CLICK_AVATAR to mNeedClickAvatar)
            },
            FRAGMENT_TAG
        )
    }

    /**
     * 收到系统消息
     */
    private fun receiveSystemMessage(message: ReceiveSingleMessage) {
        if (!isSystemMessage()) {
            return
        }
        val systemItem = mAdapter.data.getOrNull(getSystemPosition())
        if (systemItem?.command != COMMAND_SYSTEM_MESSAGE) {
            return
        }

        val sessionEntity = message.toSessionEntity(
            unreadCount = message.newSessionEntity?.unreadCount,
            strangerUnreadCount = message.newSessionEntity?.strangerUnreadCount
        )
        mAdapter.setData(getSystemPosition(), sessionEntity)
    }

    private fun receiveStrangerSingleMessage(sessionEntity: SessionEntity) {
        val strangerItem = mAdapter.data.getOrNull(getStrangerPosition())
        if (strangerItem?.command != COMMAND_STRANGER_MESSAGE) {
            return
        }

        val newSessionEntity =
            if (strangerItem.timestamp == null || (sessionEntity.timestamp != null && sessionEntity.timestamp >= strangerItem.timestamp)) {
                strangerItem.toStrangerSession(sessionEntity)
            } else {
                strangerItem.copy(
                    unreadCount = ImSessionManager.getStrangerUnreadCount()
                )
            }
        mAdapter.setData(getStrangerPosition(), newSessionEntity)
    }

    /**
     * 收到单聊消息
     */
    private fun receiveSingleMessage(message: ReceiveSingleMessage) {
        //陌生人会话列表只接受打招呼的消息
        if (!isSystemMessage() && !message.isStranger()) {
            return
        }

        val index = findSession(message.command, message.sender)
        val sessionEntity = if (index != -1) {
            mAdapter.data[index]
        } else {
            null
        }

        mViewModel.getReceiveInfoBasic(message, sessionEntity)
    }

    /**
     * 转换后条目信息
     */
    private fun invokeReceiveSingleMessage(sessionEntity: SessionEntity) {
        //如果是陌生人消息，单独处理
        if (isSystemMessage() && sessionEntity.isStranger()) {
            receiveStrangerSingleMessage(sessionEntity)
        } else {
            //如果是从陌生人转换过来的，需要尝试去除陌生人的最后消息
            if (isSystemMessage() && sessionEntity.isTranAcquaintance) {
                clearCurrentStranger(sessionEntity.otherId)
            }

            val currentPosition = findSession(sessionEntity)

            invokeUpdateSession(currentPosition, sessionEntity)
        }
    }

    private fun invokeUpdateSession(position: Int, sessionEntity: SessionEntity) {
        val topPosition = getLastTopPosition(sessionEntity.otherId)
        if (topPosition > mAdapter.data.size) {
            //理论上不可能发生
            return
        }
        //没有找到则添加到普通消息最顶端
        if (position == -1) {
            mAdapter.addData(topPosition, sessionEntity)
        } else {
            val lastItem = mAdapter.data[position]

            //如果在最顶端，直接更新
            if (mAdapter.data.size - topPosition <= 1) {
                if (sessionEntity.timestamp != null && (lastItem.timestamp == null || sessionEntity.timestamp >= lastItem.timestamp)) {
                    mAdapter.setData(position, sessionEntity)
                }
            } else {
                mAdapter.removeAt(position)
                mAdapter.addData(topPosition, sessionEntity)
            }
        }
    }

    private fun getSystemPosition() = if (isAddAnchorEntitytoTop()) 1 else 0 //系统消息
    private fun getStrangerPosition() = if (isAddAnchorEntitytoTop()) 2 else 1  //陌生人
    private fun getCustomerPosition() = if (isAddAnchorEntitytoTop()) 3 else 2    //客服下标

    /**
     * 是否已经将房主插到第一个
     */
    private fun isAddAnchorEntitytoTop(): Boolean {
        return if (mAnchorId != -1L) { //在派对房
            mAdapter.getItemOrNull(0)?.otherId == mAnchorId
        } else {
            false
        }

    }

    //查找最顶端的普通消息位置
    //目前没有客服消息所以是2，如果有客服和置顶需要往下找
    private fun getLastTopPosition(otherId: Long? = null): Int {

        if (!isSystemMessage()) return 0

        //这里是当mAnchorId不等于空那么代表是直播间观众端的半弹窗
        //要把主播默认放到第一位所以需要把要更换的用户id传过来  如果是相同那么这个session一定在第一位
        if (otherId != null && mAnchorId != -1L && otherId == mAnchorId) return 0

        // 判断是否是客服
        val isCustomer = mCustomerSessionEntity != null ||
                mAdapter.getItemOrNull(getCustomerPosition())?.command == CommonConst.Customer.command

        // 根据是否有主播 ID 计算基础位置
        val basePosition = if (isCustomer) 3 else 2

        return if (isAddAnchorEntitytoTop()) basePosition + 1 else basePosition
    }

    private fun findSession(sessionEntity: SessionEntity?): Int {
        if (sessionEntity == null) {
            return -1
        }

        return findSession(sessionEntity.command, sessionEntity.otherId)
    }

    private fun findSession(command: String, otherId: Long): Int {
        return mAdapter.data.indexOfFirst { it.command == command && it.otherId == otherId }
    }

    private fun getSessionData() {
        mViewModel.onRefresh()
    }

    private fun isSystemMessage(): Boolean {
        return mSessionCommand == COMMAND_SYSTEM_MESSAGE
    }

    fun clearStrangerUnreadCount() {
        if (!isCreated()) {
            return
        }

        mViewModel.clearStrangerAllUnreadCount()
    }

    fun greetMessageScan() {
        if (!isCreated() || !isLoadData()) {
            return
        }

        //扫描当前已经加载的是否需要转换为陌生人
        mAdapter.data.forEach {
            val timestamp = it.timestamp
            //如果是打招呼，并且时间超过1小时，转换为陌生人
            if (it.greetPushMessage == true
                && timestamp != null
                && timestamp <= CacheUtil.getServerTime() - TimeUnit.HOURS.toMillis(1)
            ) {
                ImSessionManager.switchToStranger(it)
            }
        }
    }

    override fun onAutoRefresh() {
        if (isCreated()) {
            mBinding.refreshView.recycler.scrollToPosition(0)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
    override fun onResume() {
        super.onResume()
        mViewModel.getCustomerRead()
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!hidden) {
            mViewModel.getCustomerRead()
        }
    }
    companion object {

        val FRAGMENT_TAG = "MessageDialogSingleFragment"
    }
}